package com.dx.weichat.weichat.config;

import com.dx.weichat.weichat.domain.WeatherInfo;
import com.dx.weichat.weichat.entity.WxAccessToken;
import com.dx.weichat.weichat.mapper.WeatherInfoMapper;
import com.dx.weichat.weichat.redisUtils.RedisUtil;
import com.dx.weichat.weichat.wechatUtils.WSUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;

/**
 * @author: dx
 * @date: 2018/10/7/0007
 * @description:任务调度的配置类
 */
@PropertySource("classpath:cron.props")
@Configuration
@EnableScheduling
@Service
public class ScheledCofig {
	private static Logger logger = LoggerFactory.getLogger(ScheledCofig.class);

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private WSUtil wsUtil;

	@Autowired
	private WeatherInfoMapper weatherInfoMapper;
	@Value("${wechat.accessToken.url}")
	private String access_token_url;
	//每2个小时执行一次   0 0 0/2 * * ?  每五分钟一次测试用 0 0/5 * * * ? 用于刷新获取access_token
	@Scheduled(cron = "${jobs.getAccessTokenAndSaveRedis}")
	public void getAccessTokenAndSaveRedis(){
		logger.info("========================任务调度开始 获取access_token=========================");
		String accessToken="empty";
		WxAccessToken wxAccessToken = restTemplate.getForObject(access_token_url,WxAccessToken.class);
		//ip白名单
		if(wxAccessToken.getErrcode()==null) {
			accessToken = wxAccessToken.getAccess_token();
			redisUtil.set("access_token", accessToken,7200);
		}
		logger.info("========================任务调度结束 获取到的access_token:{}=========================",accessToken);
	}

	@Scheduled(cron = "${jobs.getWXweatherAndSetRedis}")
	public void getWXweatherAndSetRedis(){
		//缓存中没有则查询
		if(redisUtil.get("weatherArea")==null) {
			Long expireTime = Long.valueOf(redisUtil.get("expireTime").toString());

			try {
				if (null != redisUtil.get("weatherArea")) {
						String jsonInfo = WSUtil.bakGetWeather("101190201");
						logger.info("获取无锡天气:{}", jsonInfo);
						JSONObject jsonResult = new JSONObject(jsonInfo);
						//获取信息成功则解析信息
						if (jsonResult.getInt("status") == 200) {
							JSONObject info = jsonResult.getJSONObject("data");
							JSONObject todayJsonInfo = info.getJSONArray("forecast").getJSONObject(0);
							redisUtil.set("weatherArea", jsonResult.getJSONObject("cityInfo").getString("city"), expireTime);
							redisUtil.set("weatherUpdateTime", todayJsonInfo.getString("ymd"), expireTime);
							redisUtil.set("weatherInfo", todayJsonInfo.getString("type"), expireTime);
							redisUtil.set("weatherTemper", todayJsonInfo.getString("low").split(" ")[1] + "~" + todayJsonInfo.getString("high").split(" ")[1], expireTime);
							redisUtil.set("weatherHumidity", info.get("shidu"), expireTime);
							redisUtil.set("weatherSunRise", todayJsonInfo.getString("sunrise"), expireTime);
							redisUtil.set("weatherSunSet", todayJsonInfo.getString("sunset"), expireTime);
							redisUtil.set("weatherFX", todayJsonInfo.getString("fx"), expireTime);
							redisUtil.set("weatherFL", todayJsonInfo.getString("fl"), expireTime);
							redisUtil.set("weatherQuality", info.getString("quality"), expireTime);
							redisUtil.set("weatherNotice", todayJsonInfo.getString("notice"), expireTime);
						} else {
							String weatherInfo = wsUtil.getWeatherInfo("无锡");
							JSONArray result = XML.toJSONObject(weatherInfo).getJSONObject("ArrayOfString").getJSONArray("string");
							logger.info("获取无锡天气:{}", weatherInfo);
							redisUtil.set("weatherArea", result.getString(0).split(" ")[1], expireTime);
							redisUtil.set("weatherUpdateTime", result.get(3), Long.valueOf(redisUtil.get("expireTime").toString()));
							redisUtil.set("weatherTemper", result.getString(8).replace("/", "~"), expireTime);
							redisUtil.set("weatherDetail1", result.get(5), expireTime);
							redisUtil.set("weatherDetail2", result.get(6), expireTime);
						}
					}
				}catch(Exception e){
					redisUtil.set("weatherArea", "error", expireTime);
					redisUtil.set("weatherUpdateTime", "error", expireTime);
					redisUtil.set("weatherTemper", "error", expireTime);
					redisUtil.set("weatherDetail1", "error", expireTime);
					redisUtil.set("weatherDetail2", "error", expireTime);

				}

		}
	}

	@Scheduled(cron = "${jobs.recordWeatherInfoEveryDay}")
	//记录每天的天气情况
	public void recordWeatherInfoEveryDay(){
		//判断redis中是否有值 无值调用上面任务插入值
		if(redisUtil.get("weatherArea")==null)
			getWXweatherAndSetRedis();
		//从redis中取值并构建对象
		WeatherInfo weatherInfo = new WeatherInfo(LocalDate.now().toString(),String.valueOf(redisUtil.get("weatherInfo")));
		weatherInfoMapper.insertWeatherInfo(weatherInfo);
		logger.info("<=====================================recordWeatherInfoEveryDay=====================================>invoke");
	}

	public void test(){



	}

}
